<template>
  <div class="flex h-full overflow-y-auto">
    <!-- 复合模型组件递归 -->
    <HComplexPages
      :isUpdate="isUpdate"
      :isChild="true"
      :preview="preview"
      :detail="detail"
      :moduleId="moduleIds"
      v-model:active="activePage"
      :pageType="pageInfo.pageType"
      :buttons="pageInfo.buttons"
      :dataSource="pageInfo.modelList"
      :parentParam="pageInfo.param"
      :parentQuery="pageInfo.query"
      :record="record"
    />
  </div>
</template>

<script lang="ts">
  import { PropType, defineComponent, ref, unref, onMounted, nextTick, watch } from 'vue';
  // import { PageWrapper } from '/@/components/Page';
  import { ModalParams } from '/@/components/ModelTable';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { useComplexContext } from '../useComplexContext';

  import { useDebounceFn } from '@vueuse/core';
  import { getModelInfoApi, getCompositeInfoApi } from '/@/api/config-center/model-design';

  export default defineComponent({
    name: 'ComModelComplex',
    components: {
      HComplexPages: createAsyncComponent(() => import('/@/components/HComplexPage/index.vue')),
    },
    props: {
      moduleId: String,
      modalParams: {
        type: Object as PropType<ModalParams>,
        default: () => ({}),
      },
    },
    setup(props) {
      const delyReload = useDebounceFn(init, 100);
      const { isUpdate, preview, moduleId, detail, record } = useComplexContext();

      onMounted(() => {
        init();
      });
      const activePage = ref(0);
      const pageInfo = ref<Indexable>({});

      const modelId = ref(props.modalParams.modelId!);
      async function getInitApi() {
        if (preview || detail) {
          return await getModelInfoApi(unref(modelId));
        }
        const params = {
          moduleId: unref(moduleId),
          modelId: unref(modelId),
        };
        return getCompositeInfoApi(params);
      }

      async function init() {
        const data = await getInitApi();

        const ret = data.compositeDesignInfo || {};

        pageInfo.value = ret;
      }

      watch(
        () => props.modalParams,
        ({ modelId: moId }) => {
          if (moId) {
            modelId.value = moId;
            nextTick(() => {
              delyReload();
            });
          }
        },
      );
      return {
        pageInfo,
        activePage,
        isUpdate,
        preview,
        detail,
        moduleIds: props.moduleId || moduleId,
        record,
      };
    },
  });
</script>
<style lang="less" scoped></style>
